package com.yunliuchain.examination.security.web.controller.admin;

import com.alibaba.fastjson.JSON;
import com.yunliuchain.examination.common.constant.Global;
import com.yunliuchain.examination.common.controller.BaseController;
import com.yunliuchain.examination.common.res.ApiResult;
import com.yunliuchain.examination.common.utils.AESUtil;
import com.yunliuchain.examination.security.cache.SecretKeyCache;
import com.yunliuchain.examination.security.req.UserLoginReq;
import com.yunliuchain.examination.system.service.UserService;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

/**
 * 用户登录控制器
 * Created by Administrator on 2018/1/4.
 */

@RestController
@RequestMapping("/yunbandan/admin/userLogin")
@Api(description = "用户登录接口")
public class UserLoginController extends BaseController {

    @Autowired
    private UserService userService;



    @Autowired
    private SecretKeyCache secretKeyCache;

    @RequestMapping(value = "/login/{loginName}",method = RequestMethod.POST)
    public ApiResult login(@PathVariable("loginName")String loginName, @RequestBody String encrypt) {
        logger.info("encrypt:"+encrypt);
        String key = Global.LOGIN_SECRET_KEY_USER + loginName;
        String secretKey = secretKeyCache.get(key);
        logger.info("secretKey:"+secretKey);
        if(StringUtils.isBlank(secretKey)){
            return ApiResult.fail("用户名或密码有误!");
        }
        try {
            String decrypt = AESUtil.decrypt(encrypt, secretKey);
            UserLoginReq loginUserReq = JSON.parseObject(decrypt, UserLoginReq.class);
            return userService.login(loginUserReq);
        } catch (Exception e) {
            e.printStackTrace();
            secretKeyCache.remove(key);
            return ApiResult.fail("用户名或密码有误");
        }

    }


    @RequestMapping(value = "/getSecretKey/{loginName}",method = RequestMethod.GET)
    public ApiResult getKey(@PathVariable("loginName")String loginName){
        String uuid = UUID.randomUUID().toString().replace("-", "").substring(0,16);
        secretKeyCache.set(Global.LOGIN_SECRET_KEY_USER +loginName,uuid);
        return ApiResult.success(uuid);
    }


}
